use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use super::technical::{IndicatorResult, MarketStateEnum, MarketAnalysis};

/// 机器学习模型类型
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum ModelType {
    /// 随机森林
    RandomForest,
    /// XGBoost
    XGBoost,
    /// LSTM神经网络
    LSTM,
    /// 集成模型
    Ensemble,
}

/// 预测时间范围
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum PredictionHorizon {
    /// 短期（分钟级）
    ShortTerm,
    /// 中期（小时级）
    MediumTerm,
    /// 长期（天级）
    LongTerm,
}

/// 预测结果置信度
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum Confidence {
    /// 非常高 (>90%)
    VeryHigh,
    /// 高 (70-90%)
    High,
    /// 中等 (50-70%)
    Medium,
    /// 低 (30-50%)
    Low,
    /// 很低 (<30%)
    VeryLow,
}

/// 市场预测结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MarketPrediction {
    /// 预测的市场状态
    pub predicted_state: MarketStateEnum,
    /// 预测的价格变动百分比
    pub price_change_prediction: f64,
    /// 预测置信度
    pub confidence: Confidence,
    /// 预测时间范围
    pub horizon: PredictionHorizon,
    /// 可能的支撑位
    pub predicted_support: Option<f64>,
    /// 可能的阻力位
    pub predicted_resistance: Option<f64>,
    /// 预测的波动率
    pub predicted_volatility: f64,
}

/// 机器学习模型配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MLModelConfig {
    /// 模型类型
    pub model_type: ModelType,
    /// 训练窗口大小
    pub training_window: usize,
    /// 预测时间范围
    pub prediction_horizon: PredictionHorizon,
    /// 特征工程配置
    pub feature_engineering: FeatureEngineeringConfig,
}

/// 特征工程配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeatureEngineeringConfig {
    /// 技术指标特征
    pub use_technical_indicators: bool,
    /// 市场微观结构特征
    pub use_market_microstructure: bool,
    /// 情绪分析特征
    pub use_sentiment_analysis: bool,
    /// 成交量分析特征
    pub use_volume_analysis: bool,
}

impl Default for MLModelConfig {
    fn default() -> Self {
        Self {
            model_type: ModelType::Ensemble,
            training_window: 1000,
            prediction_horizon: PredictionHorizon::MediumTerm,
            feature_engineering: FeatureEngineeringConfig {
                use_technical_indicators: true,
                use_market_microstructure: true,
                use_sentiment_analysis: true,
                use_volume_analysis: true,
            },
        }
    }
}

/// 机器学习预测器
pub struct MarketPredictor {
    /// 模型配置
    config: MLModelConfig,
    /// 模型状态
    model_state: HashMap<String, Vec<f64>>,
    /// 特征缓存
    feature_cache: HashMap<String, Vec<f64>>,
}

impl MarketPredictor {
    /// 创建新的市场预测器
    pub fn new(config: Option<MLModelConfig>) -> Self {
        Self {
            config: config.unwrap_or_default(),
            model_state: HashMap::new(),
            feature_cache: HashMap::new(),
        }
    }

    /// 预测市场状态
    pub fn predict(&mut self, 
        indicators: &IndicatorResult,
        current_analysis: &MarketAnalysis,
        prices: &[f64],
        volumes: &[f64],
    ) -> MarketPrediction {
        // 生成特征
        let features = self.generate_features(indicators, current_analysis, prices, volumes);
        
        // 根据模型类型进行预测
        match self.config.model_type {
            ModelType::Ensemble => self.ensemble_predict(&features),
            _ => self.single_model_predict(&features),
        }
    }

    /// 生成预测特征
    fn generate_features(&mut self,
        indicators: &IndicatorResult,
        current_analysis: &MarketAnalysis,
        prices: &[f64],
        volumes: &[f64],
    ) -> Vec<f64> {
        let mut features = Vec::new();
        
        if self.config.feature_engineering.use_technical_indicators {
            // 添加技术指标特征
            if let Some(rsi) = indicators.rsi.last() {
                features.push(*rsi);
            }
            // 添加更多技术指标...
        }

        if self.config.feature_engineering.use_market_microstructure {
            // 添加市场微观结构特征
            if !prices.is_empty() {
                let price_std = self.calculate_std(prices);
                features.push(price_std);
            }
        }

        if self.config.feature_engineering.use_volume_analysis {
            // 添加成交量分析特征
            if !volumes.is_empty() {
                let volume_ma = self.calculate_ma(volumes, 20);
                features.push(volume_ma);
            }
        }

        features
    }

    /// 集成模型预测
    fn ensemble_predict(&self, features: &[f64]) -> MarketPrediction {
        // 模拟集成预测结果
        MarketPrediction {
            predicted_state: MarketStateEnum::Neutral,
            price_change_prediction: 0.0,
            confidence: Confidence::Medium,
            horizon: self.config.prediction_horizon,
            predicted_support: None,
            predicted_resistance: None,
            predicted_volatility: 0.0,
        }
    }

    /// 单一模型预测
    fn single_model_predict(&self, features: &[f64]) -> MarketPrediction {
        // 模拟单一模型预测结果
        MarketPrediction {
            predicted_state: MarketStateEnum::Neutral,
            price_change_prediction: 0.0,
            confidence: Confidence::Medium,
            horizon: self.config.prediction_horizon,
            predicted_support: None,
            predicted_resistance: None,
            predicted_volatility: 0.0,
        }
    }

    /// 计算标准差
    fn calculate_std(&self, data: &[f64]) -> f64 {
        if data.is_empty() {
            return 0.0;
        }
        let mean = data.iter().sum::<f64>() / data.len() as f64;
        let variance = data.iter()
            .map(|&x| (x - mean).powi(2))
            .sum::<f64>() / data.len() as f64;
        variance.sqrt()
    }

    /// 计算移动平均
    fn calculate_ma(&self, data: &[f64], period: usize) -> f64 {
        if data.len() < period {
            return 0.0;
        }
        data.iter().rev().take(period).sum::<f64>() / period as f64
    }
}